<template>
  <!-- 书写html结构 -->
  <div>
    <!-- 导航栏 -->
    <van-nav-bar title="充值" left-arrow @click-left="jump('/')" />、

    <!-- 选择门店 -->
    <van-row>
      <van-col span="5" style="font-size: 16px; font-weight: bold"
        >门店名称</van-col
      >
      <van-col span="10"></van-col>
      <van-col span="9" @click="jump('PayChooseStore')"
        >{{ storeName }}
        <van-icon name="arrow" />
      </van-col>
    </van-row>
    <!-- 背景条 -->
    <van-row style="margin-top: 18px">
      <van-col
        span="24"
        style="background-color: #f8f9f9; height: 3px"></van-col>
    </van-row>
    <!-- 选择门店 -->
    <van-row style="margin-top: 15px">
      <van-col span="5" style="font-size: 16px; font-weight: bold"
        >门店余额</van-col
      >
      <van-col span="10"></van-col>
      <van-col span="9">￥{{ useramount.amount }} </van-col>
    </van-row>
    <!-- 背景条 -->
    <van-row style="margin-top: 18px">
      <van-col
        span="24"
        style="background-color: #f8f9f9; height: 3px"></van-col>
    </van-row>

    <!-- 平台说明 -->
    <van-row style="margin-top: 18px">
      <van-col
        span="24"
        style="
          font-size: 16px;
          font-weight: bold;
          text-align: left;
          padding-left: 10px;
        "
        >充值金额（资金直冲店主账户，平台不收款不负责）</van-col
      >
    </van-row>

    <!-- 选择充值金额 -->
    <van-row style="margin-top: 18px">
      <van-col v-for="item in values" :key="item">
        <van-button
          plain
          type="primary"
          style="
            border-radius: 5px;
            font-weight: 700;
            font-size: 20px;
            height: 60px;
            width: 115px;
            margin-bottom: 10px;
            margin-left: 6px;
          "
          @click="showPay(item.money, item.giveMoney)"
          >{{ item.money }}元<br />
          <span style="color: red; font-weight: 500; font-size: 14px"
            >赠送{{ item.giveMoney }}元</span
          > </van-button
        >&nbsp;&nbsp;
      </van-col>
    </van-row>

    <!-- 背景条 -->
    <van-row style="margin-top: 18px">
      <van-col
        span="24"
        style="background-color: #f8f9f9; height: 8px"></van-col>
    </van-row>

    <!-- 选择支付方式 -->
    <van-row>
      <van-col class="choosePay">选择支付方式</van-col>
    </van-row>
    <!-- 微信支付 -->
    <van-row>
      <van-col span="24">
        <van-image
          round
          width="40px"
          height="40px"
          src="https://ts1.cn.mm.bing.net/th/id/R-C.b4ae3496473df0a158d5b4927d3b74c1?rik=xVW%2fOYSozCCcrQ&riu=http%3a%2f%2fimages.shejidaren.com%2fwp-content%2fuploads%2f2020%2f03%2funnamed-file.png&ehk=N5w8ATecXx%2b1KWZ3xQORVtoIQU0Ijxz8%2bo6viRr14%2fE%3d&risl=&pid=ImgRaw&r=0"
          class="weixin-image" />
        <span class="weixin-text">微信</span>
        <van-radio-group v-model="radio" class="radio">
          <van-radio name="1"></van-radio>
        </van-radio-group>
      </van-col>
    </van-row>

    <!-- 确认选中的金额弹出层 -->
    <van-popup v-model="show" position="bottom" style="height: 50%">
      <div
        style="
          text-align: left;
          font-size: 25px;
          font-weight: 700;
          margin-top: 5%;
          margin-left: 10px;
        ">
        <van-icon name="shop-collect-o" />
        {{ storeName }}
      </div>
      <!-- 背景条 -->
      <van-row style="margin-top: 18px">
        <van-col
          span="24"
          style="background-color: #f8f9f9; height: 8px"></van-col>
      </van-row>
      <div
        style="
          text-align: center;
          font-size: 50px;
          font-weight: 700;
          margin-top: 10%;
        ">
        {{ payMoney }} <span style="font-size: 20px">元</span>
      </div>
      <div
        style="
          text-align: center;
          font-size: 18px;
          font-weight: 700;
          margin-top: 0%;
          color: #07c160;
        ">
        赠送金额 {{ freeMoney }}
        <span style="font-size: 18px"
          >元，应到账金额：{{ accountMoney }}元</span
        >
      </div>
      <van-button
        round
        type="info"
        style="width: 90%; margin-top: 10%"
        @click="toPay"
        >立即充值</van-button
      >
    </van-popup>

    <!--二维码支付模块-->
    <div id="qrcode" style="margin-top: 20px; margin-left: 30%"></div>

    <!-- 我的余额按钮 -->
    <van-button
      round
      type="info"
      style="width: 90%; margin-top: 30px"
      @click="toMyBalance"
      >我的余额</van-button
    >
  </div>
</template>

<script>
import QRCode from "qrcodejs2";
//书写组件配置项目 相当于写js代码的地方
//要求template必须有且只有一个根元素，如果有两个就不知道绑定那个
export default {
  //export default 相当于过去的new vue ({el:"#div"})
  //全部都是json格式

  props: {
    //注册属性，用来父子组件传递参数使用
  },
  data() {
    //定义数据的地方
    return {
      storeName: "请选择门店", //门店名称
      storeId: "", //门店id
      userId: "", //用户id
      radio: "1", //单选框默认选中
      useramount: {amount:'0.00'}, //用户余额
      values: [
        {
          money: 30,
          giveMoney: 0.0,
        },
        {
          money: 50,
          giveMoney: 10.0,
        },
        {
          money: 100,
          giveMoney: 20.0,
        },
        {
          money: 200,
          giveMoney: 60.0,
        },
        {
          money: 300,
          giveMoney: 120.0,
        },
        {
          money: 400,
          giveMoney: 180.0,
        },
      ], //金额列表

      checked: false, //复选框默认不选
      show: false, //弹出层默认不显示

      payMoney: 0, //支付金额
      freeMoney: 0, //赠送金额
      accountMoney: 0, //实际到账金额
      //微信支付二维码
      code_url: "",
    };
  },
  created() {
    this.storeId = this.$route.query.storeId;
    console.log("获取的门店id:" + this.storeId);
    this.selectByToken();
    //判断门店id是否为null
    if (this.storeId != null) {
      //执行查询门店名称的方法
      this.selectStoreName();
    }
  },

  mounted() {},

  methods: {
   

    //根据token查询当前登录用户信息
    selectByToken() {
      var _this = this;
      console.log("根据token查询当前登录用户信息。。。。。");
      this.$http
        .get("/tuser/queryBy")
        .then(function (response) {
          console.log(JSON.stringify(response));
          if (response.data.code == 200) {
            _this.userId = response.data.data.id; //获取用户id
          }
        })
        .catch(function (error) {
          _this.$toast("获取用户id出错。。。");
        });
    },
    //点击充值金额按钮后触发的函数
    showPay(money, giveMoney) {
      //1,判断是否选择门店
      if (this.storeName == "请选择门店") {
        this.$toast("请先选择门店");
      } else {
        //获取金额
        this.payMoney = money;
        this.freeMoney = giveMoney;
        this.accountMoney = money + giveMoney;
        this.show = true;
      }
    },

    //去支付
    toPay() {
      this.show = false; //把显示金额的弹窗关闭
      this.getPayment();
    },

    //获取支付的二维码信息
    getPayment() {
      let _this = this;
      //生成明细id
      var detailNo = "car" + new Date().getTime();
      this.$http
        .post("/pay/getNativeCodeUrl", {
          rechargeMoney: this.payMoney,
          discountsMoney: this.giveMoney,
          accountMoney: this.accountMoney,
          storeId: this.storeId,
          userId: this.userId,
          detailId: detailNo,
        })
        .then(function (response) {
          console.log("获取支付的二维码。。。。。");
          console.log(JSON.stringify(response.data));
          if (response.data.code == 200) {
            //赋值给微信支付
            _this.code_url = response.data.data.code_url;
            //让付款二维码显示
            _this.getCoed();

            //定时器获取订单状态,每隔三秒执行一次
            _this.timer = setInterval(() => {
              //判断是否付款
              _this.queryPayStatus(detailNo);
            }, 3000);
          } else {
            setTimeout(function () {
              this.$router.push("/login"); //跳转登录页面
            }, 1000); // 定时时间
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    //让二维码显示
    getCoed() {
      let qrcode = new QRCode("qrcode", {
        width: 150, // 宽
        height: 150, // 高
        text: this.code_url, // 二维码内容,也可以直接放接口获取的数据
      });
    },

    //判断是否付款
    queryPayStatus(detailNo) {
      var _this = this;
      this.$http
        .get("/pay/getPayStatus/" + detailNo)
        .then(function (response) {
          console.log("查看是否付款。。。。。。。");
          console.log(JSON.stringify(response.data));
          console.log(response.data.data.trade_state_desc);
          //获取支付状态
          _this.paystatus = response.data.data.trade_state_desc;
          if (_this.paystatus == "支付成功") {
            //调用修改订单状态的方法
            //if (_this.paystatus == "支付成功") {
            clearInterval(_this.timer);
            //添加到我的余额中
             _this.addBalance(detailNo) 
          }
        });
    },

    //充值的金额添加余额中
    addBalance(detailNo) {
      var _this = this;
      console.log("把充值的金额添加余额中。。。。。");
      // console.log(JSON.stringify("detailId....." + detailNo));
      this.$http
        .post("/balance/update", {
          balanceId:this.useramount.balanceId,
          storeId: this.storeId,
          userId: this.userId,
          amount: this.accountMoney+this.useramount.amount,
        })
        .then(function (response) {
          console.log(JSON.stringify(response));
          if (response.data.code == 200) {
            // alert(response.data.code);
            //跳转到支付成功页面
            //调用添加明细的方法
            _this.addDetail(detailNo);
          }
        })
        .catch(function (error) {
          _this.$toast("出错了。。。");
        });
    },

    //添加到我的明细表里
    addDetail(detailNo) {
      var _this = this;
      console.log("把充值的金额添加到明细表中。。。。。");
      // console.log(JSON.stringify("detailId....." + detailNo));
      this.$http
        .post("/userDetail/add", {
          rechargeMoney: this.payMoney,
          discountsMoney: this.giveMoney,
          accountMoney: this.accountMoney,
          storeId: this.storeId,
          userId: this.userId,
          detailId: detailNo,
        })
        .then(function (response) {
          console.log(JSON.stringify(response));
          if (response.data.code == 200) {
            // alert(response.data.code);
            //跳转到支付成功页面
            _this.goSuccessPay(_this.storeName, _this.payMoney);
          }
        })
        .catch(function (error) {
          _this.$toast("出错了。。。");
        });
    },

    //去支付成功页面
    goSuccessPay(storeName, payMoney) {
      //跳转页面时传参,把实际支付金额和店铺名称传进去
      this.$router.push({
        path: "/successPay",
        query: { storeName: storeName, payMoney: payMoney },
      });
    },

    //根据门店id查询门店名称
    selectStoreName() {
      var _this = this;
      this.$http
        .get("/tbStore/queryById?id=" + this.storeId)
        .then(function (response) {
          console.log("根据门店id查询门店名称。。。。。");
          console.log(JSON.stringify(response));
          if (response.data.code == 200) {
            _this.storeName = response.data.data[0].storeName; //获取用户名
            _this.queryaaa();
          }
        })
        .catch(function (error) {
          //alert(JSON.stringify(error));
          _this.$toast("出错了。。");
        });
    },
      //根据用户编号和门店编号查询余额
    queryaaa() {
      var _this = this;
      console.log("根据token查询当前登录用户信息。。。。。");
      this.$http
        .get(
          "/balance/queryUserAndStore?userId=" +
            this.userId +
            "&storeId=" +
            this.storeId
        )
        .then(function (response) {
          console.log(JSON.stringify(response));
          if (response.data.code == 200) {
            if (response.data.data == null) {
              _this.add(_this.storeId);
            } else {
              _this.queryUserAndStore();
            }
          }
        })
        .catch(function (error) {
          _this.$toast("获取用户余额错了。。。");
        });
    },
    //添加用户绑定余额和详情
    add(radio) {
      var _this = this;
      this.$http
        .post(
          "/balance/addBalanceIna?userId=" + this.userId + "&storeId=" + radio
        )
        .then(function (response) {
          console.log(JSON.stringify(response));
          //alert(JSON.stringify(response));
          if (response.data.data == 200) {
            _this.queryUserAndStore();
          }
        })
        .catch(function (error) {
          console(error);
          _this.$toast.error("你错了。。。");
        });
    },

 //获取用户余额
    queryUserAndStore() {
      var _this = this;
      console.log("根据token查询当前登录用户信息。。。。。");
      this.$http
        .get(
          "/balance/queryUserAndStore?userId=" +
            this.userId +
            "&storeId=" +
            this.storeId
        )
        .then(function (response) {
          console.log(JSON.stringify(response));
          if (response.data.code == 200) {
            _this.useramount = response.data.data; //获取用户id
          }
        })
        .catch(function (error) {
          _this.$toast("获取用户余额错了。。。.....");
        });
    },


    //跳转到我的余额页面
    toMyBalance() {
      if (this.storeId!=null) {
        this.$router.push({ path: "/Balance", query: { storeId:this.storeId } });
      } else {
        this.$router.push({ path: "/Balance"});
      }
    },

    //  方法事件处理
    jump(uri) {
      this.$router.push(
        uri,
      );
    },
  },
  components: {},
};
</script>

<style scoped>
/* 编写样式的 */
.goods-card {
  margin: 0;
  background-color: white;
}
.delete-button {
  height: 100%;
}
/*选择支付方式css */
.choosePay {
  color: black;
  font-size: 20px;
  font-weight: bold;
  text-align: left;
  margin-left: 15px;
  margin-top: 20px;
  margin-bottom: 20px;
}
/* 微信支付css */
.weixin-image,
.weixin-text {
  float: left;
  margin-left: 15px;
}
.weixin-text {
  font-size: 18px;
  color: black;
  margin-top: 5px;
}
/* 单选框css */
.radio {
  float: right;
  margin-right: 15px;
}
</style>
